﻿using System;
using System.Data;

namespace KC.Business.Text.Parsers
{
	public class DataTranslator
	{
		/// <summary>Translates a DataTable using another DataTable as a key.</summary>
		/// <param name="dtData">DataTable containing data to translate.</param>
		/// <param name="TranslateMatrix">DataTable to use as a Translation Key. Uses Columns ColumnName, OldValue, NewValue</param>
		/// <returns>Translated DataTable.</returns>
		public static DataTable TranslateTable(DataTable dtData, DataTable TranslateMatrix)
		{
			if (dtData == null) throw new ArgumentNullException("dtData");
			if (TranslateMatrix == null) throw new ArgumentNullException("TranslateMatrix");
			if (dtData.Rows.Count == 0 || TranslateMatrix.Rows.Count == 0) return dtData;

			for (int x = 0; x < dtData.Rows.Count; x++)
				for (int y = 0; y < dtData.Columns.Count; y++)
					dtData.Rows[x][y] = TranslateCell(TranslateMatrix, dtData.Rows[x][y].ToString(), dtData.Columns[y].ColumnName);
			return dtData;
		}
		/// <summary>Translates a cell of a table within a translation loop.</summary>
		/// <param name="TranslateMatrix">Translation Matrix</param>
		/// <param name="cell">Cell text to Translate</param>
		/// <param name="ColumnName">Name of Column being Translated (Used for cross reference)</param>
		/// <returns>Translated value for cell</returns>
		protected static string TranslateCell(DataTable TranslateMatrix, string cell, string ColumnName)
		{
			if (TranslateMatrix == null) throw new ArgumentNullException("TranslateMatrix");
			if (string.IsNullOrEmpty(cell)) throw new ArgumentNullException("cell");
			if (string.IsNullOrEmpty(ColumnName)) throw new ArgumentNullException("ColumnName");

			if (TranslateMatrix.Rows.Count == 0) return cell;
			for (int i = 0; i < TranslateMatrix.Rows.Count; i++)
				if (TranslateMatrix.Rows[i]["ColumnName"].ToString().ToLower().Trim() == ColumnName.ToLower().Trim())
					cell = cell.Replace(TranslateMatrix.Rows[i]["OldValue"].ToString(), TranslateMatrix.Rows[i]["NewValue"].ToString());
			return cell;
		}
	}
}